<template>
  <div class="app-container">


    <!-- 表格组件 -->
    <ex-tree-table
      ref="exTreeTable"
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading.sync="loading"
      @handleCreateEmit="handleCreateEmit"
      @handleUpdateEmit="handleUpdateEmit"
      @handleRmoveColEmit="handleRmoveColEmit"
      @handleAddSonNodeEventEmit="handleAddSonNodeEventEmit"
      @handleCorrelationFactorEventEmit="handleCorrelationFactorEventEmit"
      @handlePricingMethodEventEmit="handlePricingMethodEventEmit"
      @handleCustomerBehaviorEventEmit="handleCustomerBehaviorEventEmit"
      @handleSchedulingItemScopeEventEmit="handleSchedulingItemScopeEventEmit"
      @handleCopySonNodeEventEmit="handleCopySonNodeEventEmit"
      >
    </ex-tree-table>


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData.sync="formSubmitData"
      :parentNodeName="parentNodeName"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
      @handleFromAddSonNodeEmit="handleFromAddSonNodeEmit"
      @resetFormDataEmit="resetFormSubmitData"
      >
    </submit-form>

    <!-- 关联因子 CorrelationFactorTabs -->
    <correlation-factor-tabs
      ref="correlationFactorTabs"
      :textMap="textMap"
      :currentRow="currentRow"
      :sonCurrentRow="sonCurrentRow"
      :factorSelected="factorSelected"
      :dialogCorrelationFactorTabsVisible.sync="dialogCorrelationFactorTabsVisible"
    >
    </correlation-factor-tabs>

    <!-- 定价方法 PricingMethodForm -->
    <pricing-submit-form
      ref="pricingsubmitForm"
      :dialogFormVisible.sync="pricingDialogFormVisible"
      dialogStatus="udateSave"
      :formSubmitData="pricingFormSubmitData"
      :pricingOptions="pricingOptions"
      :currentRow="currentRow"
      :sonCurrentRow="sonCurrentRow"
      :pricingChangesOptons="pricingChangesOptons"
      :isCustAction.sync="isCustAction"
      :watchPricingFormSubmitData="watchPricingFormSubmitData"
      @handleFromUpdateSaveDataEmit="handlePricingFromUpdateDataEmit"
      @resetFormDataEmit="pricingResetFormDataEmit"
      @findFindcurvetermEmit2="findFindcurveterm"
      >
    </pricing-submit-form>



    <!-- 调度项范围 -->
    <el-dialog
      title="调度项范围"
      width="827px"
      :visible.sync="dialogSchedulingFactorVisible"
      append-to-body
      >
      <SchedulingFactor
        :titles="['未选','已选']"
        :value.sync="schedulingFactorValue"
        :data="schedulingFactorData"
        :currentRow="currentRow"
        @factortransferEmit="schedulingFactorEmit"
        />
    </el-dialog>


    <!-- 客户行为 CustomerBehavior -->
    <customer-behavior-submit-form
      ref="customerBehaviorSubmitForm"
      :dialogFormVisible.sync="customerBehaviorDialogFormVisible"
      dialogStatus="udateSave"
      :formSubmitData="customerBehaviorFormSubmitData"
      :currentRow="currentRow"
      :sonCurrentRow="sonCurrentRow"
      :custActionOptions="custActionOptions"
      :pmDatetypeOptions="pmDatetypeOptions"
      @handleFromUpdateSaveDataEmit="handlecustomerBehaviorFromUpdateDataEmit"
      @resetFormDataEmit="customerBehaviorResetFormDataEmit"
      >
    </customer-behavior-submit-form>

    <!-- 子节点复制 -->
    <copy-son-node-submit-form
      ref="copySonNodeSubmitForm"
      :dialogFormVisible.sync="copySonNodeSubmitFormVisible"
      dialogStatus="udateSave"
      :formSubmitData="copySonNodeSubmitFormSubmitData"
      :currentRow="currentRow"
      :sonCurrentRow="sonCurrentRow"
      @handleFromUpdateSaveDataEmit="handleCopySonNodeSubmitFormUpdateDataEmit"
      @resetFormDataEmit="copySonNodeSubmitFormResetFormDataEmit"
      >
    </copy-son-node-submit-form>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils from 'xe-utils'

import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'

import {
  addcoazhu,
  addcoazi,
  daletecoa,
  findadjtype,
  findcurveterm,
  findcustaction,
  findpricingmethod,
  findtransfercurvegp,
  findunit,
  fingpubcoa,
  pricingmethod,
  updatecoa,
  findAdjustmentitemcodename,
  findAdjustmentitemcodenamein,
  addAdjustmentitem,
  findcoacustaction,
  findpmdatetype,
  adddcustaction,
  selectcustaction,
  copycoazi,
  addcoaCodeZi,
  addcoaCode
} from './service/baseApi'
// 基础表格组件
import ExTreeTable from './components/ExTreeTable'

// 文章表单
import SubmitForm from './components/SubmitForm'
// 关联因子
import CorrelationFactorTabs from './components/CorrelationFactorTabs'
// 定价方法
import PricingSubmitForm from './components/PricingSubmitForm/index'
// 调度项范围
import SchedulingFactor from './components/SchedulingFactor'
// 客户行为
import CustomerBehaviorSubmitForm from './components/CustomerBehaviorSubmitForm'
// 子节点复制
import CopySonNodeSubmitForm from './components/CopySonNodeSubmitForm'
export default {
  name: 'vxe-basetable',
  mixins: [resetFormSubmitData],
  components: {
    //PageHeaderLayout,
    ExTreeTable,
    SubmitForm,
    CorrelationFactorTabs,
    PricingSubmitForm,
    SchedulingFactor,
    CustomerBehaviorSubmitForm,
    CopySonNodeSubmitForm
  },
  props: {
    /* 当前选中方案 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    },
    /* 当前选中方案的已选因子 */
    factorSelected: {
      type: Array,
      default() {
        return []
      }
    }
  },
  // 定义属性
  data() {
    return {
      /* 弹框状态-调度项范围 */
      dialogSchedulingFactorVisible: false,
      schedulingFactorValue: [],
      schedulingFactorData: [],
      /* 客户行为 */
      customerBehaviorDialogFormVisible: false,
      customerBehaviorFormSubmitData:{
        cust_action:'',  //客户行为
        pm_date_type:'', //罚息计算日
      },
      custActionOptions:[], //客户信息Options
      pmDatetypeOptions:[], //罚息计算日Options



      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      parentNodeName: '',  //父级节点名称
      // 表单数据对象
      formSubmitData: {
        id: undefined,
        coa_code: '',
        coa_name: '',
        parent_coa_code: '',
        status: '',
      },
      initFormSubmitData: {
        id: "",
        coa_code: '',
        coa_name: '',
        parent_coa_code: '',
        status: '1',
      },
      /* 表格相关 */
      tableColumn: [], // 表格字段
      loading: false, //表格loading特效
      tableData: [],  //表格数据
      /* 关联因子 */
      textMap: "XXX关联因子",  /*  TOTO:  子组件弹框标题待定 */
      dialogCorrelationFactorTabsVisible: false,
      /* 当前选中节点 */
      sonCurrentRow: {},

      /* 定价方法 */
      // 表单数据
      pricingFormSubmitData: {
        id: undefined,
        cust_action: '',
      },
      // initFormSubmitDataPricing: {
      //   id: '',
      //   cust_action: '',
      // },
      // 表单数据-只作用于监听数据变化（防止监听内改变监听数据死循环）
      watchPricingFormSubmitData: {
        id: '',
        cust_action: '',
      },
      pricingDialogFormVisible: false, //弹框是否显示
      pricingOptions: [],  // 定价方法options
      pricingChangesOptons: {}, //定价方法可变表单项相关的options
      isCustAction: false,  //是否回显数据 

      /* 子节点复制 */
      copySonNodeSubmitFormVisible:false,
      copySonNodeSubmitFormSubmitData:{
        node_id:'',
        s_date:''
      },


    } //datareturn-end

  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {},
  // 监控data中的数据变化
  watch: {
    currentRow() {
      this.findList()
    }
  },
  // 方法集合
  methods: {
    /* API数据操作相关 */
    // 获取首节点编码
    async getAddcoaCode() {
      return await addcoaCode({
        m_id:this.currentRow.id
      }).then(({data}) => {
        return data.rows.coa_code
      })
    },
    // 获取子节点编码
    async getAddcoaCodeZi(parent_coa_code) {
      return await addcoaCodeZi({
        m_id:this.currentRow.id,
        parent_coa_code
      }).then(({data}) => {
        return data.rows.coa_code
      })
    },

    // 查询数据
    findList() {
      this.loading = true
      // console.log(' this.formSearchData:::', this.formSearchData);
      // 请求表格数据

      fingpubcoa({
        m_id: this.currentRow.id
      }).then(({data}) => {
        // console.log('response:....', data);
        // 给表格数据赋值
        const treeData = XEUtils.toArrayTree(data.rows, {
          key: 'coa_code',
          parentKey: 'parent_coa_code',
        })
        // console.log('treeDatatreeData', treeData);
        this.tableData = treeData
        // 关闭加载特效
        setTimeout(() => {
          this.loading = false
        }, 0.5 * 1000)
      })
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols() {
      const tabCols = [  //动态增加的字段 传进来的
        // { type: 'seq', width: 60, fixed: null },
        // { type: 'checkbox', width: 50, fixed: null },
        {field: 'coa_name', title: '节点名称', width: 250, treeNode: true, fixed: 'left'},
        // { field: 'ID', title: '主键', width: 200 , showOverflow: true},
        {field: 'coa_code', title: '节点编码', width: 300},
        {field: 'vaild_time', title: '有效时间段', width: 400, sortable: true},
        {field: 'name', title: '定价方法', width: 200},
        {
          field: 'status', title: '状态', width: 300, formatter(obj) {
            console.log('formatterformatter', obj);
            if (obj.cellValue === 0) {
              return "无效"
            } else {
              return "有效"
            }
          }
        }
      ]
      this.tableColumn = tabCols;
    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type) {
      this.getAddcoaCode().then((coa_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            coa_code
          }
        })
        this.parentNodeName = '首'
        this.dialogStatus = type
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
    handleUpdateEmit(row, type) {
      let {children, mod_date, mod_us_code, ...params} = Object.assign({}, row) // copy obj
      console.log('item:', params);
      params = XEUtils.objectMap(params, item => {
        return (XEUtils.isNull(item)) ? '' : item
      })
      console.log('item2:', params);
      this.formSubmitData = params
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row) {
      console.log('delrow:', row);
      if (row.children.length > 0) {
        this.$message.error('删除失败:还有子集！');
        return false;
      }
      daletecoa({
        ...row
      }).then(({data}) => {
        // this.dialogFormVisible = false
        // this.$refs.exTreeTable.$refs.xTree.remove(row)
        this.findList()
      })

    },
    // 行内按钮-新增子节点
    handleAddSonNodeEventEmit(row, type) {

      this.getAddcoaCodeZi(row.coa_code).then((coa_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            parent_coa_code: row.coa_code, //曲线名称,
            coa_code:coa_code
          },
        })
        this.parentNodeName = row.coa_name
        this.dialogStatus = type
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })
    },

    /* 表单组件相关 */
    // 修改节点
    handleFromUpdateDataEmit() {
      updatecoa({
        ...this.formSubmitData
      }).then(({data}) => {
        this.dialogFormVisible = false
        this.findList()
      })

    },
    // 新增首节点
    handleFromCreateDataEmit() {

      addcoazhu({
        m_id: this.currentRow.id,
        ...this.formSubmitData
      }).then(({data}) => {
        // this.dialogFormVisible = false
        this.findList()
        this.getAddcoaCode().then((coa_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            coa_code
          }
        })
        this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })


      })
    },
    // 新增子节点
    handleFromAddSonNodeEmit() {
      addcoazi({
        m_id: this.currentRow.id,
        ...this.formSubmitData
      }).then(({data}) => {
        // this.dialogFormVisible = false
        this.findList()
        console.log(this.formSubmitData);
        this.getAddcoaCodeZi(this.formSubmitData.parent_coa_code).then((coa_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            parent_coa_code:this.formSubmitData.parent_coa_code, //曲线名称,
            coa_code:coa_code
          },
        })
        this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })

      })
    },
    /**
     * 关联因子
     * @param {Object} row 当前定价规则节点数据
     */
    handleCorrelationFactorEventEmit(row) {
      if (!XEUtils.isEmpty(this.factorSelected)) {
        this.sonCurrentRow = Object.assign({}, row)
        this.dialogCorrelationFactorTabsVisible = true
      }else{
        this.$message({
          message: '没有关联的因子',
          type: 'warning'
        });
      }
      
    },
    /**
     * 定价方法
     * @param {Object} row 当前定价规则节点数据
     */
    handlePricingMethodEventEmit(row) {
      console.log('rreee',row);
      this.sonCurrentRow = Object.assign({}, row)
      // 获取回显数据
      this.findFindpricingmethod(this.sonCurrentRow.id)
      this.pricingDialogFormVisible = true

    },
    // 定价方法修改数据
    handlePricingFromUpdateDataEmit() {
      console.log('this.pricingFormSubmitData',this.pricingFormSubmitData);
      this.addAndUpdatePricingmethod(this.pricingFormSubmitData)
    },
    // 定价方法表单重置
    pricingResetFormDataEmit() {

    },
    // 获取定价方法
    findFindcustaction() {
      findcustaction().then(({data}) => {
        this.pricingOptions = data.rows
        console.log('获取定价方法', data);
      })
    },
    //  获取定价方法回显数据
    findFindpricingmethod(id) {
      findpricingmethod({
        id
      }).then(({data}) => {
        this.pricingFormSubmitData =  Object.assign({}, data.rows) 
        this.watchPricingFormSubmitData = Object.assign({}, data.rows) 
        if (!XEUtils.isEmpty(data.rows)) {
          this.isCustAction = true
        }
      })
    },
    // 转移曲线组下拉框
    findFindtransfercurvegp() {
      findtransfercurvegp().then(({data}) => {
        this.$set(this.pricingChangesOptons, 'transfercurvegpOptions',Object.assign({}, data.rows))
        console.log('转移曲线组下拉框', data);
      })
    },



    // 期限点下拉框
    findFindcurveterm(cv_gp_code) {
      findcurveterm({
        cv_gp_code
      }).then(({data}) => {
        this.$set(this.pricingChangesOptons, 'curvetermOptions',Object.assign({}, data.rows))
        // this.pricingChangesOptons.curvetermOptions =Object.assign({}, data.rows)
        console.log('期限点下拉框', data);
      })
    },
    // 取点方法下拉框
    findFindadjtype() {
      findadjtype().then(({data}) => {
        this.$set(this.pricingChangesOptons, 'adjtypeOptions',Object.assign({}, data.rows))
        // this.pricingChangesOptons.adjtypeOptions =Object.assign({}, data.rows)
        console.log('取点方法下拉框', data);
      })
    },
    // 保底单位下拉框
    findFindunit() {
      findunit().then(({data}) => {
        this.$set(this.pricingChangesOptons, 'unitOptions',Object.assign({}, data.rows))
        // this.pricingChangesOptons.unitOptions =Object.assign({}, data.rows)
        console.log('保底单位下拉框', data);
      })
    },
    // 增加&修改 定价方法
    addAndUpdatePricingmethod(dataParams) {
      pricingmethod({
        m_id: this.sonCurrentRow.id,
        ...dataParams
      }).then(() => {
       this.findList()
      })
    },

    /**
     * 客户行为相关
     */
    handleCustomerBehaviorEventEmit(row){
      this.sonCurrentRow = Object.assign({}, row)
      // 获取回显数据
      this.findSelectcustaction(this.sonCurrentRow.id)

      this.customerBehaviorDialogFormVisible = true
    },
    // 客户行为Options
    findFindcoacustaction() {
      findcoacustaction().then(({data}) => {
        this.custActionOptions = data.rows
        console.log('this.custActionOptionsthis.custActionOptions',this.custActionOptions);
      })
    },
    // 罚息计算日Options
    findFindpmdatetype() {
      findpmdatetype().then(({data}) => {
        this.pmDatetypeOptions = data.rows
      })
    },
    // 查询某节点客户行为数据
    findSelectcustaction(id) {
      selectcustaction({id}).then(({data}) => {
        console.log('查询某节点客户行为数据',data);
        this.customerBehaviorFormSubmitData = Object.assign({}, data.rows)
      })
    },
    // 客户行为表单提交
    addAndUpdateadddcustaction(dataParams) {
      adddcustaction({
        id: this.sonCurrentRow.id,
        ...dataParams
      })
    },
    // 客户行为数据修改
    handlecustomerBehaviorFromUpdateDataEmit(){
      this.addAndUpdateadddcustaction(this.customerBehaviorFormSubmitData)
    },
    customerBehaviorResetFormDataEmit(){},

    /**
     * 调度项范围
     */
    /* 
      dialogSchedulingFactorVisible: false,
      schedulingFactorValue: [1001],
      schedulingFactorData
    */
    // 调度项范围-全量数据
    findFindAdjustmentitemcodename() {
      findAdjustmentitemcodename().then(({data}) => {
        this.schedulingFactorData = XEUtils.map(data.rows, (item) => {
          return {
            label: `${item.code}-${item.name}`,
            key: item.code,
            disabled: false
          }
        })
      })
    },
    // 调度项范围-已选数据
    findFindAdjustmentitemcodenamein() {
      findAdjustmentitemcodenamein({id: this.sonCurrentRow.id}).then(({data}) => {
        this.schedulingFactorValue = []
        XEUtils.arrayEach(data.rows, (item, key) => {
          this.schedulingFactorValue.push(item.code)
        })
      })
    },
    // 调度项范围-已选修改
    modifyAddAdjustmentitem(adj_type) {
      addAdjustmentitem({
        id: this.sonCurrentRow.id,
        adj_type
      })
    },
    // 调整项弹框
    handleSchedulingItemScopeEventEmit(row){
      this.sonCurrentRow = Object.assign({}, row)
      // 获取回显数据
      this.findFindAdjustmentitemcodename()
      this.findFindAdjustmentitemcodenamein()
      this.dialogSchedulingFactorVisible = true
    },
    // 调整项修改
    schedulingFactorEmit(val){
      console.log('val调整项修改val',val);
      this.modifyAddAdjustmentitem(val.join(','))
    },
    // 子节点复制
    handleCopySonNodeEventEmit(row){
      this.copySonNodeSubmitFormSubmitData.s_date = ''
      this.sonCurrentRow = Object.assign({}, row)
      this.copySonNodeSubmitFormVisible = true
    },
    // 子节点复制提交
    handleCopySonNodeSubmitFormUpdateDataEmit(){
      this.copySonNodeSubmitFormSubmitData.node_id = this.sonCurrentRow.id
      copycoazi({
        ...this.copySonNodeSubmitFormSubmitData
      }).then(()=>{
         this.findList()
      })
    },
    // 子节点复制重置表单
    copySonNodeSubmitFormResetFormDataEmit(){
      this.copySonNodeSubmitFormSubmitData.s_date = ''
    },

    /**
     *  重置表单内容-
     *  obj ：重置默认值 {replaceObj,resetObj,exclude}
     */
    //  resetFormSubmitDataPricing(obj = {}) {
    //   let newObj, resetObj, replaceObj, exclude
    //   // 没有重置对象默认重置所有值 isUndefined
    //   if (XEUtils.isUndefined(obj.resetObj) || XEUtils.isEmpty(obj.resetObj)) {
    //     resetObj = XEUtils.isEmpty(this.initFormSubmitDataPricing)? {} : this.initFormSubmitDataPricing
    //   } else {
    //     resetObj = obj.resetObj
    //   }
    //   // 替换（重置值）中的值：比如修改时需要回显的值
    //   replaceObj = obj.replaceObj || {}
    //   newObj = XEUtils.merge(resetObj, replaceObj)
    //   // 排除不重置的字段
    //   if (!XEUtils.isUndefined(obj.exclude) && !XEUtils.isEmpty(obj.exclude)) {
    //     exclude = obj.exclude
    //     XEUtils.arrayEach(exclude, (item, key) => {
    //       delete newObj[`${item}`];
    //     })
    //   }
    //   this.pricingFormSubmitData = XEUtils.merge(this.pricingFormSubmitData, newObj)

    // },


  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

    // 初始化表格字段
    this.initTableCols()
    // 初始化表格数据
    this.findList()
    // 获取定价方法
    this.findFindcustaction()
    /* 定价方法切换表单options数据 */
    this.findFindtransfercurvegp()
    // this.findFindcurveterm()
    this.findFindadjtype()
    this.findFindunit()
    /* 客户行为表单Options数据 */
    this.findFindcoacustaction()
    this.findFindpmdatetype()

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {

  },
  beforeCreate() {
  }, // 生命周期 - 创建之前
  beforeMount() {
  }, // 生命周期 - 挂载之前
  beforeUpdate() {
  }, // 生命周期 - 更新之前
  updated() {
  }, // 生命周期 - 更新之后
  beforeDestroy() {
  }, // 生命周期 - 销毁之前
  destroyed() {
  }, // 生命周期 - 销毁完成
  activated() {
  }, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>


.my-dropdown4 {
  width: 600px;
  height: 300px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>